package chatroom;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class ChatroomClient {

    public static void main(String[] args) {
        //创建线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup(2);
        try {
            //创建启动对象
            Bootstrap bootstrap = new Bootstrap();
            //设置线程组
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //设置处理器
                            socketChannel.pipeline().addLast(new StringEncoder())
                                    .addLast(new StringDecoder())
                                    .addLast(new ChatroomClientHandler());
                        }
                    });
            //连接服务器
            ChannelFuture channelFuture = bootstrap.connect("192.168.1.102", 8888).sync();
            Scanner scanner = new Scanner(System.in);
            //打字聊天
            while(scanner.hasNext()){
                String msg = scanner.next();
                channelFuture.channel().writeAndFlush(msg);
            }
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}

/**
 * 客户端处理器
 */
class ChatroomClientHandler extends SimpleChannelInboundHandler<String>{

    //打印服务器发送的消息
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println(s);
    }
}
